<template>
  <BaseMainSlot>
    <template v-slot:searchbox>
      <div class="seach-box">
        <div class="select-box-content">
          <div class="select-box-content-name">设备类型：</div>
          <el-cascader
            ref="cascader"
            v-model="equipmentTypeCode"
            clearable
            :options="equipmentTypeList"
            placeholder="请选择设备类型"
            :props="defaultProps"
            @change="changeCascader"
          />
        </div>
        <div class="select-box-content">
          <div class="select-box-content-name">设备名称：</div>
          <el-input
            v-model="equipmentName"
            placeholder="请输入设备名称"
            clearable
            @change="queryPageList()"
          />
        </div>
        <div class="select-box-content">
          <div class="select-btns table-btns" @click.stop="changeSelect()">
            <i class="el-icon-circle-check"></i>
            <p v-if="activeName === '1'">收起更多查询</p>
            <p v-if="activeName === ''">更多查询</p>
          </div>
        </div>
        <el-collapse v-model="activeName" accordion @change="handleChange">
          <el-collapse-item name="1">
            <div class="select-box-content">
              <div class="select-box-content-name">设备型号：</div>
              <div
                class="select-box-content-all"
                @click="cancelSelect('model')"
              >全部</div>
              <div
                v-for="(item, index) in equModelArr"
                :key="index"
                class="select-box-content-list"
                :style="{
                  color:
                    equModelCode === item.equModelCode ? '#54DEE2' : '#C1CFD2',
                  fontWeight: equModelCode === item.equModelCode ? '600' : '400'
                }"
                @click="selectEquModelCode(item)"
              >{{ item.modelName }}</div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </template>
    <template v-slot:btnsBar></template>
    <template v-slot:typenodeslot>
      <SelectButton @topitemtype="topitemtype" />
    </template>
    <template v-slot:content>
      <ActionBar
        :add-active="addActive"
        :del-active="delActive"
        :has-del="false"
        :page-no="138"
        @add="add"
        @del="del"
      />
      <el-table
        ref="tableData"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        stripe
        border
        height="calc(100% - 50px)"
        :row-key="
          row => {
            return row.equipmentCode;
          }
        "
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" :reserve-selection="true" />
        <el-table-column type="index" label="序号" width="50">
          <template
            slot-scope="scoped"
          >{{ scoped.row.equipmentCode ? scoped.$index + 1 : "" }}</template>
        </el-table-column>
        <el-table-column prop="equipmentName" label="设备名称" />
        <el-table-column prop="modelName" label="所属设备型号" />
        <el-table-column prop="modelName" label="质保日期" />
        <el-table-column prop="status" label="状态" width="100">
          <template v-if="scoped.row.equipmentCode" slot-scope="scoped">
            <!-- <div v-if="scoped.row.status==='启用'" class="start-info-btn">{{ scoped.row.status }}</div>
            <div v-else-if="scoped.row.status==='停用'" class="stop-info-btn">{{ scoped.row.status }}</div>-->
            <div
              v-if="scoped.row"
              :class="{
                'start-info-btn': scoped.row.status === '启用',
                'stop-info-btn': scoped.row.status === '禁用'
              }"
            >{{ scoped.row.status }}</div>
            <div v-else>{{ "未获取设备状态" }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="450">
          <template v-if="scoped.row.equipmentCode" slot-scope="scoped">
            <div class="table-btns-box">
              <div
                v-if="judgePermission(138, 'edit')"
                class="table-btns edit-btns"
                @click="edit(scoped.row)"
              >
                <i class="el-icon-edit-outline"></i>
                <p>修改</p>
              </div>
              <!-- <div class="table-btns del-btns" @click="delOne(scoped.row)">
                <i class="el-icon-delete"></i>
                <p>删除</p>
              </div>-->
              <div
                v-if="
                  scoped.row.status === '禁用' && judgePermission(138, 'start')
                "
                class="table-btns add-btns"
                @click="start(scoped.row)"
              >
                <i class="el-icon-open"></i>
                <p>启用</p>
              </div>
              <div
                v-if="
                  scoped.row.status === '启用' && judgePermission(138, 'stop')
                "
                class="table-btns del-btns"
                @click="stop(scoped.row)"
              >
                <i class="el-icon-turn-off"></i>
                <p>停用</p>
              </div>
              <div
                v-if="judgePermission(138, 'info')"
                class="table-btns detail-btns"
                @click="completeInfo(scoped.row)"
              >
                <i class="el-icon-circle-check"></i>
                <p>设备详情</p>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
      <AddEditDialog
        ref="addEditDialog"
        :now-chance-stau="nowChanceStau"
        :equ-model-arr="equModelArr"
        :title-text="titleText"
        :edit-object="editObject"
        :show.sync="showAddEditDialog"
        @closeDialog="closeDialog"
        @cancelDialog="cancel"
      />
      <CompleteInfoDialog
        ref="CompleteInfoDialog"
        :now-chance-stau="nowChanceStau"
        :equ-model-arr="equModelArr"
        :edit-object="editObject"
        :show.sync="showCompleteInfoDialog"
        @closeDialog="closeDialog"
        @cancelDialog="cancel"
      />
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar/index.vue";
import Pagination from "@/components/Pagination";
import SelectButton from "@/components/equipTypeSelectButton/typeSelectParentButton.vue";
import BaseMainSlot from "@/components/BaseMainSlot/kong-new.vue";
import AddEditDialog from "./components/add-edit-dialog.vue";
import CompleteInfoDialog from "./components/complete-info-dialog.vue";
import equipStandingBookApi from "@/api/processing-management/equip-manage/equip-standing-book";
import equipModelApi from "@/api/processing-management/equip-manage/equip-model";
import equipTypeApi from "@/api/processing-management/equip-manage/equip-type/index";
import { mapGetters } from "vuex";
import { mymixin } from "@/utils/mixin";
export default {
  name: "EquipStandingBook",
  components: {
    Pagination,
    ActionBar,
    SelectButton,
    BaseMainSlot,
    AddEditDialog,
    CompleteInfoDialog
  },
  mixins: [mymixin],
  data() {
    return {
      //  搜索条件:设备名称
      equipmentName: "",
      //  搜索条件:设备型号
      modelName: "",
      //  搜索条件:设备类型
      equipmentTypeCode: "",
      // 设备类型数组
      equipmentTypeList: [],
      defaultProps: {
        children: "childList",
        value: "equipmentTypeCode",
        label: "equipmentTypeName",
        emitPath: false,
        checkStrictly: true
      },
      //  搜索条件:查询条件
      equModelCode: "",
      // 设备型号数组
      equModelArr: [],
      // 删除数组
      checkedIdList: [],
      // 当前的农机设备还是物联设备
      topitemtypeId: 0,
      showAddEditDialog: false,
      showCompleteInfoDialog: false
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    tableData(v) {}
  },
  created() {},
  mounted() {},
  methods: {
    // 展开筛选框
    handleChange(val) {
      this.activeName = val;
    },
    // 关闭选择框
    changeCascader() {
      this.$refs.cascader.dropDownVisible = false;
      console.log(this.equipmentTypeCode);
      if (this.equipmentTypeCode) {
        this.queryEquipModel(this.equipmentTypeCode);
      }
      this.queryPageList();
    },
    // 清空选项
    cancelSelect(data) {
      if (data === "model") {
        this.equModelCode = "";
      }
      this.queryPageList();
    },
    // 选择
    selectEquModelCode(item) {
      if (this.equModelCode === item.equModelCode) {
        this.equModelCode = "";
      } else {
        this.equModelCode = item.equModelCode;
      }
      this.queryPageList();
    },
    // 设备模型
    queryEquipModel(date) {
      this.loading = false;
      // 获取数据
      equipModelApi.queryAllEquModel(date).then(res => {
        this.loading = false;
        if (res.code === 1) {
          let data = res.data || [];
          this.equModelArr = [];
          for (var i in data) {
            this.equModelArr.push({
              modelName: data[i],
              equModelCode: i
            });
          }
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 转换设备型号编号到名字
    changeModelNameByEquModelCode(v) {
      var index = this.equModelArr.findIndex(item => item.equModelCode === v);
      if (index !== -1) {
        return this.equModelArr[index]["modelName"];
      }
    },
    // 关联设备类型，根据父级查询子级
    queryEquipmentType() {
      this.loading = false;
      // 获取数据
      equipTypeApi.querySubAll(this.topitemtypeId).then(res => {
        this.loading = false;
        if (res.code === 1) {
          let data = res.data || [];
          this.equipmentTypeList = data;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 获取点击的农机设备、物联设备
    topitemtype(e) {
      this.topitemtypeId = e;
      // 获取表格数据
      this.tableData = [];
      this.equModelArr = [];
      this.queryPageList();
      this.queryEquipModel(e);
      this.queryEquipmentType();
    },
    async queryPageList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          // 设备类型 农机设备/物联设备
          equipmentTypeCode: this.topitemtypeId
        }
      };
      if (this.equipmentName) {
        params.entity["equipmentName"] = this.equipmentName;
      }
      console.log(this.equipmentTypeCode);
      if (this.equipmentTypeCode) {
        params.entity["equipmentTypeCode"] = this.equipmentTypeCode;
      }
      if (this.equModelCode) {
        params.entity["equModelCode"] = this.equModelCode;
      }
      await equipStandingBookApi.queryPageList(params).then(res => {
        this.loading = false;
        // 赋值总条数
        console.log(res);
        if (res.code === 1) {
          let data = res.data || {};
          this.totalSize = data.totalElements;
          // 赋值数组
          this.tableData = data.content;
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      // this.queryPageList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.queryPageList();
    },
    handleSelectionChange(list) {
      this.checkedIdList = [];
      let notvalue = true;
      let emptyList = [];
      this.checkedIdList = list.map(item => {
        if (item.equipmentCode) {
          return item.equipmentCode;
        } else {
          notvalue = false;
          emptyList.push(item);
          return "";
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
        this.toggleNoSelection(emptyList);
        return;
      }
      if (this.checkedIdList.length >= 1) this.delActive = true;
      else this.delActive = false;
    },
    // 单个删除
    delOne(data) {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          var form = new FormData();
          form.append("equipmentCodeList", data.equipmentCode);
          equipStandingBookApi.delList(form).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.queryPageList();
              this.resetActionBar();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    delmessage() {
      var form = new FormData();
      this.checkedIdList.forEach(a => {
        form.append("equipmentCodeList", a);
      });
      equipStandingBookApi.delList(form).then(res => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          this.queryPageList();
          this.resetActionBar();
        }
      });
    },
    // 添加
    add() {
      this.nowChanceStau = "add";
      this.titleText = "添加";
      this.addActive = false;
      this.delActive = false;
      this.editActive = false;
      this.showAddEditDialog = true;
    },
    // 修改
    edit(row) {
      if (row.equipmentCode) {
        this.editObject = JSON.parse(JSON.stringify(row));
        this.nowChanceStau = "edit";
        this.titleText = "修改";
        this.addActive = false;
        this.delActive = false;
        this.showAddEditDialog = true;
      } else {
        this.editObject = {};
      }
    },
    completeInfo(row) {
      if (row.equipmentCode) {
        this.editObject = JSON.parse(JSON.stringify(row));
        this.showCompleteInfoDialog = true;
      }
    },
    // 启用
    start(data) {
      this.$confirm("确认启用该设备?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          var form = {
            status: "ENABLE",
            equModelCode: data.equModelCode,
            equipmentCode: data.equipmentCode,
            equipmentName: data.equipmentName,
            modelName: data.modelName,
            operationMode: data.operationMode,
            repairNodeId: data.repairNodeId,
            selfDriving: data.selfDriving
          };
          equipStandingBookApi.edit(form).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.queryPageList();
              this.resetActionBar();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 停用
    stop(data) {
      this.$confirm("确认停用该设备?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          var form = {
            status: "DISABLE",
            equModelCode: data.equModelCode,
            equipmentCode: data.equipmentCode,
            equipmentName: data.equipmentName,
            modelName: data.modelName,
            operationMode: data.operationMode,
            repairNodeId: data.repairNodeId,
            selfDriving: data.selfDriving
          };
          equipStandingBookApi.edit(form).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.queryPageList();
              this.resetActionBar();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    closeDialog() {
      this.queryPageList();
      this.cancel();
    },
    cancel() {
      this.showAddEditDialog = false;
      this.showCompleteInfoDialog = false;
      this.nowChanceStau = "";
      this.titleText = "";
      this.editObject = {};
      this.addActive = true;
      this.delActive = false;
      this.editActive = false;
      this.$refs.tableData.setCurrentRow();
      this.$refs.tableData.clearSelection();
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";

::v-deep .el-collapse-item__header {
  height: 0px;
}
::v-deep .el-collapse-item__content {
  padding-bottom: 10px;
}
::v-deep .el-pagination {
  position: absolute;
  right: 0px;
  bottom: -18px;
}

::v-deep .el-form-item__label {
  min-width: 120px !important;
  text-align: end;
}

// ::v-deep .staff-manage .common-layout {
//   margin-top: 15px;
// }

.total {
  position: absolute;
  top: 25px;
  left: 300px;
}

::v-deep .el-form-item.is-error {
  .el-input__inner {
    border-color: #f56c6c !important;
  }
}

// ::v-deep .butt-list-sty {
//   position:absolute;
//   transform: translateY(-150%) !important;
//   // z-index: 99;
//   width: 30% !important;
//   .basebut1 {
//   transform: translateY(0%) !important;

//   }
//   .basebut2 {
//     transform: translateY(0%) !important;
//   }
// }

// ::v-deep .butt-list-stys {
//   position:absolute;
//   transform: translateY(-30%) !important;
//   z-index: 99;
//   .basebut1 {
//   transform: translateY(0%) !important;

//   }
//   .basebut2 {
//     transform: translateY(0%) !important;
//   }
// }
// ::v-deep .parameteClass {
// //  .el-form-item__label {
// //   min-width: 120px !important;
// //   text-align: end;
// //   }
//     // border: 1px dashed #d9d9d9;
//     // padding: 2px 2px;
//     display: flex;
//     flex-wrap: wrap;
//     justify-content: space-between
// }
</style>
